<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceStatus">
        <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态" clearable>
          <el-option
              v-for="dict in device_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
          <el-option
            v-for="dict in device_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['coal:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['coal:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleTypeThreshold"
            v-hasPermi="['coal:thresholdData:list']"
        >阈值设定</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['coal:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['coal:device:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编号" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="deviceName" width="200" :show-overflow-tooltip="true"/>
      <el-table-column label="设备状态" align="center" prop="deviceStatus" width="80">
        <template #default="scope">
          <dict-tag :options="device_status" :value="scope.row.deviceStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="deviceType" width="80">
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.deviceType"/>
        </template>
      </el-table-column>
      <el-table-column label="设备组" align="center" width="100" prop="parentGroupName" />
      <el-table-column label="设备子组" align="center" width="140" prop="childGroupName" />
<!--      <el-table-column label="带速" align="center" prop="speed" />
      <el-table-column label="密度" align="center" prop="density" />-->
      <el-table-column label="连接IP" align="center" prop="ip" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="连接端口" align="center" prop="port" />
<!--      <el-table-column label="创建者" align="center" prop="createBy"/>-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="更新者" align="center" prop="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" width="100" show-overflow-tooltip prop="remark" />-->
      <el-table-column label="操作" width="150" fixed="right" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
<!--          <el-tooltip content="修改" placement="top">
            <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['coal:device:edit']"
            ></el-button>
          </el-tooltip>-->
          <el-tooltip content="设备阈值设定" placement="top">
            <el-button
                link
                type="primary"
                icon="Setting"
                @click="handleThreshold(scope.row)"
                v-hasPermi="['coal:thresholdData:list']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="参数设置" placement="top">
            <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleParam(scope.row)"
                v-hasPermi="['coal:device:param']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['coal:device:remove']"
            ></el-button>
          </el-tooltip>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备分组" prop="deviceGroupTye">
          <el-select v-model="form.deviceGroupTye" placeholder="请选择设备分组" @change="changeDeviceGroup">
            <el-option
                v-for="dict in device_group"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备组" prop="parentGroupName">
          <el-autocomplete
              v-model="form.parentGroupName"
              :fetch-suggestions="querySearch"
              clearable
              class="inline-input w-50"
              placeholder="请输入设备组"
              @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="设备子组" prop="childGroupName">
          <el-autocomplete
              v-model="form.childGroupName"
              :fetch-suggestions="childQuerySearch"
              clearable
              class="inline-input w-50"
              placeholder="请输入设备子组"
              @select="childHandleSelect"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="form.deviceType" placeholder="请选择设备类型">
            <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
<!--        <el-form-item label="带速" prop="speed" v-if="form.deviceType === 3">
          <el-input v-model="form.speed" placeholder="请输入带速" />
        </el-form-item>
        <el-form-item label="密度" prop="density" v-if="form.deviceType === 3">
          <el-input v-model="form.density" placeholder="请输入密度" />
        </el-form-item>-->
        <el-form-item label="连接ip" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入连接ip" />
        </el-form-item>
        <el-form-item label="连接port" prop="port">
          <el-input v-model="form.port" placeholder="请输入连接port" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName" v-if="form.deviceType === 4">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="form.deviceType === 4">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="通道号" prop="channel" v-if="form.deviceType === 4">
          <el-input v-model="form.channel" placeholder="请输入通道号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <Param v-if="propOpen"
           :prop-device-id="propDeviceId"
           :prop-open="propOpen"
           :prop-device-type="propDeviceType"
           :prop-param-type="propParamType"
           @closeParam="closeParam"></Param>
  </div>
</template>

<script setup name="Device">
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/coal/device";
import { getGroupInfo, getChildGroupInfo } from "@/api/coal/deviceGroup";
import Param from './param.vue'

const { proxy } = getCurrentInstance();
const { device_type,device_group,device_status,binocular_radar_function,sieve_radar_function } = proxy.useDict('device_type','device_group','device_status',"binocular_radar_function","sieve_radar_function");
const router = useRouter();

const deviceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const propDeviceId = ref(null);
const propDeviceType = ref(null);
const propOpen = ref(false);
const propParamType = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: null,
    deviceStatus: null,
    deviceType: null,
    deviceGroup: null,
    speed: null,
    density: null,
    ip: null,
    port: null,
  },
  rules: {
    deviceGroupTye: [
      { required: true, message: "设备组类型不能为空", trigger: "change" }
    ],
    parentGroupName: [
      { required: true, message: "设备组不能为空", trigger: "change" }
    ],
    /*childGroupName: [
      { required: true, message: "设备子组不能为空", trigger: "change" }
    ],*/
    deviceName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    deviceType: [
      { required: true, message: "设备类型不能为空", trigger: "change" }
    ],
    speed: [
      { required: true, message: "带速不能为空", trigger: "blur" }
    ],
    density: [
      { required: true, message: "密度不能为空", trigger: "blur" }
    ],
    ip: [
      { required: true, message: "连接ip不能为空", trigger: "blur" }
    ],
    port: [
      { required: true, message: "连接port不能为空", trigger: "blur" }
    ],
    userName: [
      { required: true, message: "用户名不能为空", trigger: "blur" }
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" }
    ],
    channel: [
      { required: true, message: "通道号不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "创建者不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    updateBy: [
      { required: true, message: "更新者不能为空", trigger: "blur" }
    ],
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 查询设备表列表 */
function getList() {
  loading.value = true;
  listDevice(queryParams.value).then(response => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deviceName: null,
    deviceType: null,
    deviceGroup: null,
    parentGroupName: null,
    childGroupName: null,
    speed: null,
    density: null,
    ip: null,
    port: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("deviceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDevice(_id).then(response => {
    form.value = response.data;
    changeDeviceGroup(form.value.parentGroupId)
    open.value = true;
    title.value = "修改设备表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备表编号为"' + _ids + '"的数据项？').then(function() {
    return delDevice(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coal/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}

getList();

const restaurants = ref([])
const childRestaurants = ref([])
function changeDeviceGroup(val){
  getGroupInfo(val).then(resp =>{
    restaurants.value = resp.data
  });
}

function handleSelect(item){
  getChildGroupInfo(item.id).then(resp =>{
    childRestaurants.value = resp.data
  });
}

function childHandleSelect(item){
}

function querySearch (queryString, cb) {
  const results = queryString && queryString !== "null"
      ? restaurants.value.filter( restaurant=> restaurant.value.indexOf(queryString) === 0)
      : restaurants.value
  cb(results)
}

function childQuerySearch(queryString, cb) {
  const results = queryString && queryString !== "null"
      ? childRestaurants.value.filter( restaurant=> restaurant.value.indexOf(queryString) === 0)
      : childRestaurants.value
  cb(results)
}

function handleThreshold(row){
  if (row.deviceType !== 3 && row.deviceType !== 5){
    proxy.$modal.msg("该设备无需设置阈值");
    return
  }
  router.push({ path: "/facility/deviceThreshold",query: { 'deviceType': row.deviceType, 'deviceId':row.id, 'deviceName':row.deviceName} });
}

function handleTypeThreshold(){
  router.push({ path: "/facility/threshold" });
}

function handleParam(row){
  propDeviceId.value = row.id
  propDeviceType.value = row.deviceType

  if (propDeviceType.value === 3){
    propParamType.value = binocular_radar_function.value.filter(item => item.type === '2')
  } else if (propDeviceType.value === 5){
    propParamType.value = sieve_radar_function.value.filter(item => item.type === '2')
  } else {
    propParamType.value = []
  }
  propOpen.value = true
}

function closeParam(){
  propOpen.value = false
}

</script>
